package com.axiyue.action;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;

import net.shopxx.bean.SystemConfig;
import net.shopxx.bean.SystemConfig.StoreFreezeTime;
import net.shopxx.common.CommentUtil;
import net.shopxx.entity.Order;
import net.shopxx.entity.OrderItem;
import net.shopxx.entity.OrderLog;
import net.shopxx.entity.Product;
import net.shopxx.entity.Order.OrderStatus;
import net.shopxx.entity.Order.PaymentStatus;
import net.shopxx.entity.Order.ShippingStatus;
import net.shopxx.entity.OrderLog.OrderLogType;
import net.shopxx.service.HtmlService;
import net.shopxx.service.OrderLogService;
import net.shopxx.service.OrderService;
import net.shopxx.service.ProductService;
import net.shopxx.util.SystemConfigUtil;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;

import chinapnr.SecureLink;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.web.ServletCacheAdministrator;
import com.opensymphony.xwork2.ActionSupport;

@ParentPackage("axiyue")
public class PaymentAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = -2783364706147729379L;
	@Resource
	OrderService orderService;
	@Resource
	private OrderLogService orderLogService;
	@Resource
	private ProductService productService;
	@Resource
	private HtmlService htmlService;

	private String id;// 订单
	private String message;

	public String paynotify() {

		try {
			getRequest().setCharacterEncoding("GBK");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String CmdId = getRequest().getParameter("CmdId"); // 消息类型
		String MerId = getRequest().getParameter("MerId"); // 商户号
		String RespCode = getRequest().getParameter("RespCode"); // 应答返回码
		String TrxId = getRequest().getParameter("TrxId"); // 钱管家交易唯一标识
		String OrdAmt = getRequest().getParameter("OrdAmt"); // 金额
		String CurCode = getRequest().getParameter("CurCode"); // 币种
		String Pid = getRequest().getParameter("Pid"); // 商品编号
		String OrdId = getRequest().getParameter("OrdId"); // 订单号
		String MerPriv = getRequest().getParameter("MerPriv"); // 商户私有域
		String RetType = getRequest().getParameter("RetType"); // 返回类型
		String DivDetails = getRequest().getParameter("DivDetails"); // 分账明细
		String GateId = getRequest().getParameter("GateId"); // 银行ID
		String ChkValue = getRequest().getParameter("ChkValue"); // 签名信息

		try {
			// 验签
			String MerKeyFile = CommentUtil.class.getClassLoader().getResource(
					"").getPath()
					+ "PgPubk.key";
			String MerData = CmdId + MerId + RespCode + TrxId + OrdAmt
					+ CurCode + Pid + OrdId + MerPriv + RetType + DivDetails
					+ GateId; // 参数顺序不能错
			SecureLink secureLink = new SecureLink();
			int ret = secureLink.SignMsg(MerId, MerKeyFile, MerData);
			if (ret != 0) {

			} else {
				if (RespCode.equals("000000")) {
					// 交易成功
					// 根据订单号 进行相应业务操作
					// 在些插入代码
					id = OrdId;
					Order order = orderService.load(id);
					if (order == null) {
						System.out.println("no order");
						return "error";
					}
					// 库存处理
					if (getSystemConfig().getStoreFreezeTime() == StoreFreezeTime.payment
							&& order.getPaymentStatus() == net.shopxx.entity.Order.PaymentStatus.unpaid
							&& order.getShippingStatus() == ShippingStatus.unshipped) {
						for (OrderItem orderItem : order.getOrderItemSet()) {
							Product product = orderItem.getProductitem()
									.getProduct();
							if (product.getStore() != null) {
								product.setFreezeStore(product.getFreezeStore()
										+ orderItem.getProductQuantity());
								productService.update(product);
								if (product.getIsOutOfStock()) {
									flushCache();
									htmlService
											.productContentBuildHtml(product);
								}
							}
						}
					}
					order.setOrderStatus(OrderStatus.processed);
					order.setPaymentStatus(PaymentStatus.paid);
					order.setPaidAmount(new BigDecimal(OrdAmt));
					orderService.update(order);

					// 订单日志
					OrderLog orderLog = new OrderLog();
					orderLog.setOrderLogType(OrderLogType.payment);
					orderLog.setOrderSn(order.getOrderSn());
					orderLog.setOperator("");
					orderLog.setInfo("支付金额：" + OrdAmt);
					orderLog.setOrder(order);
					orderLogService.save(orderLog);
					message="支付成功";
				} else {
					// 交易失败
					// 根据订单号 进行相应业务操作
					// 在些插入代码
					message="支付失败";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "notify";
	}

	public String payret() {

		try {
			getRequest().setCharacterEncoding("GBK");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String CmdId = getRequest().getParameter("CmdId"); // 消息类型
		String MerId = getRequest().getParameter("MerId"); // 商户号
		String RespCode = getRequest().getParameter("RespCode"); // 应答返回码
		String TrxId = getRequest().getParameter("TrxId"); // 钱管家交易唯一标识
		String OrdAmt = getRequest().getParameter("OrdAmt"); // 金额
		String CurCode = getRequest().getParameter("CurCode"); // 币种
		String Pid = getRequest().getParameter("Pid"); // 商品编号
		String OrdId = getRequest().getParameter("OrdId"); // 订单号
		String MerPriv = getRequest().getParameter("MerPriv"); // 商户私有域
		String RetType = getRequest().getParameter("RetType"); // 返回类型
		String DivDetails = getRequest().getParameter("DivDetails"); // 分账明细
		String GateId = getRequest().getParameter("GateId"); // 银行ID
		String ChkValue = getRequest().getParameter("ChkValue"); // 签名信息

		try {
			// 验签
			String MerKeyFile = CommentUtil.class.getClassLoader().getResource(
					"").getPath()
					+ "PgPubk.key";
			String MerData = CmdId + MerId + RespCode + TrxId + OrdAmt
					+ CurCode + Pid + OrdId + MerPriv + RetType + DivDetails
					+ GateId; // 参数顺序不能错
			SecureLink secureLink = new SecureLink();
			int ret = secureLink.SignMsg(MerId, MerKeyFile, MerData);
			if (ret != 0) {

			} else {
				if (RespCode.equals("000000")) {
					// 交易成功
					// 根据订单号 进行相应业务操作
					// 在些插入代码
					id = OrdId;
					Order order = orderService.load(id);
					if (order == null) {
						System.out.println("no order");
						return "error";
					}
					// 库存处理
					if (getSystemConfig().getStoreFreezeTime() == StoreFreezeTime.payment
							&& order.getPaymentStatus() == net.shopxx.entity.Order.PaymentStatus.unpaid
							&& order.getShippingStatus() == ShippingStatus.unshipped) {
						for (OrderItem orderItem : order.getOrderItemSet()) {
							Product product = orderItem.getProductitem()
									.getProduct();
							if (product.getStore() != null) {
								product.setFreezeStore(product.getFreezeStore()
										+ orderItem.getProductQuantity());
								productService.update(product);
								if (product.getIsOutOfStock()) {
									flushCache();
									htmlService
											.productContentBuildHtml(product);
								}
							}
						}
					}
					order.setOrderStatus(OrderStatus.processed);
					order.setPaymentStatus(PaymentStatus.paid);
					order.setPaidAmount(new BigDecimal(OrdAmt));
					orderService.update(order);

					// 订单日志
					OrderLog orderLog = new OrderLog();
					orderLog.setOrderLogType(OrderLogType.payment);
					orderLog.setOrderSn(order.getOrderSn());
					orderLog.setOperator("");
					orderLog.setInfo("支付金额：" + OrdAmt);
					orderLog.setOrder(order);
					orderLogService.save(orderLog);
					message="支付成功";
				} else {
					// 交易失败
					// 根据订单号 进行相应业务操作
					// 在些插入代码
					message="支付失败";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "ret";
	}

	// 获取系统配置信息
	public SystemConfig getSystemConfig() {
		return SystemConfigUtil.getSystemConfig();
	}

	// 更新页面缓存
	private void flushCache() {
		Cache cache = ServletCacheAdministrator.getInstance(
				getRequest().getSession().getServletContext()).getCache(
				getRequest(), PageContext.APPLICATION_SCOPE);
		cache.flushAll(new Date());
	}

	// 获取Request
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	// 获取Response
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	
}
